import React, { FC, useEffect, useRef, useState, } from "react";
import { Row, Col, Tabs, Button, Table, Divider, Switch, Form, Input, message, Checkbox ,Upload} from 'antd';
import type { ColumnsType } from 'antd/lib/table';
import '../../static/css/App.css'
import '../../static/css/system/system.css'
import img from '../../static/images/QRcide.jpg'

import { Field, Edit ,Settinglist} from '../../apis/system' //封装接口
// 上传图片
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';


interface DataType {
    key: React.Key;
    name: string;
    age: number;
    address: string;
}

const System: FC = () => {
    const setin:any = useRef()
    //上传图片
    const getBase64 = (img: RcFile, callback: (url: string) => void) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result as string));
        reader.readAsDataURL(img);
      };
      
      const beforeUpload = (file: RcFile) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
          message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
      };
      const [loading, setLoading] = useState(false);
      const [imageUrl, setImageUrl] = useState<string>('http://localhost:3000/static/media/logining.254af08746ef38a3a328.jpg');
    
      const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
          setLoading(true);
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          getBase64(info.file.originFileObj as RcFile, url => {
            setLoading(false);
            setImageUrl(url);
          });
        }
      };
    
      const uploadButton = (
        <div>
          {loading ? <LoadingOutlined /> : <PlusOutlined />}
          <div style={{ marginTop: 8 }}>Upload</div>
        </div>
      );
          
    //   网站系统设置
    const getlist =async () => {
        const res:any = await Settinglist()
        if(res.code==='00000'){
            console.log(res);
            setin.current.setFieldsValue(res.data[0])
            console.log(setin);
            setImageUrl(res.data[0].minibanner)
            
        }
    }


    //表单
    const layout = {
        labelCol: { span: 8 },
        wrapperCol: { span: 16 },
    };
    //1表单
    const onFinissh = (values: any) => {
        console.log('Success:', values);
    };

    const onFinishFailed = (errorInfo: any) => {
        console.log('Failed:', errorInfo);
    };
    /* eslint-disable no-template-curly-in-string */
    const validateMessages = {
        // required: '${label} is required!',
    };

    //快关点击添加
    const onFinish = (e: any) => {
        console.log(e);
        if (idd) {
            Edit(
                {
                    "id": idd, //有id表示 编辑 没有id 表示添加
                    "formdata": {
                        "fieldname": e.fieldname,
                        "is_null": e.is_null
                    }
                }
            ).then((res: any) => {
                // console.log(res);
                if (res.code === '00000') {
                    setjudeg(true)
                    message.success("修改成功")
                    field()
                    setidd("")

                }

            })
        } else {
            Edit(
                {
                    "id": '', //有id表示 编辑 没有id 表示添加
                    "formdata": {
                        "fieldname": e.fieldname,
                        "is_null": e.is_null
                    }
                }
            ).then((res: any) => {
                // console.log(res);
                if (res.code === '00000') {
                    setjudeg(true)
                    message.success("添加成功")
                    field()

                }

            })
        }

    };

    const { TabPane } = Tabs;
    const onChange = (key: string) => {
    };
    useEffect(() => {
        field()
        getlist()
    }, [])

    //添加修改按钮
    const [judeg, setjudeg] = useState(true)
    const click = () => {
        setjudeg(!judeg)
        setidd("")
    }

    //系统设置表字段
    const [info, setinfo] = useState()
    const field = async () => {
        const res: any = await Field()
        // console.log(res);
        if (res.code === '00000') {
            setinfo(res.data)

        }
    }
    //修改
    const [idd, setidd]: any = useState()
    const upda = (e: any) => {
        return () => {
            // console.log(e);
            setidd(e)
            setjudeg(!judeg)
        }
    }


    //添加开关
    const onChanges = (checked: boolean) => {
        console.log(`switch to ${checked}`);

    };
    // 表格
    const columns: any = [
        {
            title: '核销人员姓名',
            dataIndex: 'fieldname',
            render: (text: string) => <a>{text}</a>,
        },
        {
            title: '是否启用',
            dataIndex: 'is_null',
            render: (text: number) => {
                if (text === 1) {
                    return <div> <Switch defaultChecked /></div>
                } else {
                    return <div> <Switch /></div>
                }
            }

        },
        {
            title: '操作',
            dataIndex: 'id',
            render: (text: string) => (
                <div><Button type="primary" className="upda" onClick={upda(text)}>修改</Button><Button type="primary" danger className="dele">删除</Button></div>
            )
        },
    ];

    const data: any = [
        {
            fieldname: 'John Brown',
            is_null: 32,
        },
    ];

    // rowSelection object indicates the need for row selection
    const rowSelection = {
        onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        },
        getCheckboxProps: (record: DataType) => ({
            disabled: record.name === 'Disabled User', // Column configuration not to be checked
            name: record.name,
        }),
    };







    return (
        <div className="system">
            <Tabs defaultActiveKey="1" onChange={onChange} className="Tabs">
                <TabPane tab="网站设置" key="1">
                    <Row>
                        <Col span={8}>
                            <Form
                                name="basic"
                                labelCol={{ span: 8 }}
                                wrapperCol={{ span: 16 }}
                                initialValues={{ remember: true }}
                                onFinish={onFinissh}
                                onFinishFailed={onFinishFailed}
                                autoComplete="off"
                                ref={setin}
                            >
                                <Form.Item label="网站名称" name="sitename" rules={[{ required: true }]}>
                                    <Input />
                                </Form.Item>
                                <Form.Item label="网站url" name="url" rules={[{ required: true }]}>
                                    <Input />
                                </Form.Item>
                                <Form.Item label="关键字" name="keywords" rules={[{ required: true }]}>
                                    <Input />
                                </Form.Item>
                                <Form.Item label="简介" name="desc" rules={[{ required: true }]}>
                                    <Input />
                                </Form.Item>
                                <Form.Item label="版权" name="copyright" rules={[{ required: true }]}>
                                    <Input />
                                </Form.Item>
                                <Form.Item label="小程序ID" name="miniappid" rules={[{ required: true }]}>
                                    <Input />
                                </Form.Item>
                                <Form.Item label="小程序密钥" name="minisecret" rules={[{ required: true }]}>
                                    <Input />
                                </Form.Item>
                                <Form.Item label="公众号ID" name="appid" rules={[{ required: true }]}>
                                    <Input />
                                </Form.Item>
                                <Form.Item label="公众号密钥" name="appsecret" rules={[{ required: true }]}>
                                    <Input />
                                </Form.Item>
                                <Form.Item label="微信小程序图片" name="minibanner" rules={[{ required: true }]}>
                                    <Upload
                                        name="avatar"
                                        listType="picture-card"
                                        className="avatar-uploader"
                                        showUploadList={false}
                                        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                        beforeUpload={beforeUpload}
                                        onChange={handleChange}
                                        >
                                        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' ,height:"100%"}} /> : uploadButton}
                                    </Upload>
                                </Form.Item>
                                <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                                    <Button type="primary" htmlType="submit">
                                      提交
                                    </Button>
                                </Form.Item>
                            </Form>
                        </Col>
                    </Row>
                </TabPane>
                <TabPane tab="离校二维码" key="2">
                    <div>
                        <div className="QRimg">
                            <img src={img} alt="" className="img" />
                            <div className="downdiv"><span className="download">下载二维码</span></div>
                        </div>

                    </div>
                </TabPane>
                <TabPane tab="Form表单设置" key="3" className="sysAdd">
                    <Row>
                        {judeg ? <Col span={24}><Button type="primary" className="addbutton" onClick={click}>添加</Button></Col> : <Col span={24}><Button type="primary" className="addbuttons" ghost={true} onClick={click}>返回</Button></Col>}

                    </Row>

                    <div style={{ marginTop: "20px",marginLeft:'16px' }}>
                        {judeg ? <Table
                            rowSelection={{
                                ...rowSelection,
                            }}
                            columns={columns}
                            dataSource={info}
                            bordered={true}
                            pagination={false}
                            rowKey="id"
                        /> : <div>
                            <Form {...layout} name="nest-messages" onFinish={onFinish} validateMessages={validateMessages}>
                                <Form.Item name='fieldname' label="Form表单名" rules={[{ required: true }]} className="inp  ">
                                    <Input />
                                </Form.Item>
                                <Form.Item name='is_null' label="是否开启" className="inp">
                                    <Switch onChange={onChanges} />
                                </Form.Item>
                                {idd
                                    ? <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }} className="inpp">
                                        <Button type="primary" htmlType="submit">
                                            修改
                                        </Button>
                                    </Form.Item> :
                                    <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }} className="inpp">
                                        <Button type="primary" htmlType="submit">
                                            添加
                                        </Button>
                                    </Form.Item>
                                }
                            </Form>
                        </div>}

                    </div>
                </TabPane>
            </Tabs>
        </div>
    )
}

export default System